/**
 * @description 密码键盘
 * @author liuyongwei
 */

import { View, Input, Text } from '@tarojs/components';
import Taro, { FC, useState } from '@tarojs/taro';
import * as styles from './index.module.less';
import classnames from 'classnames';

/**
 * @num 密码框的数量
 * @titleText 支付密码的title
 * @callBack 输入密码后的callBack
 * @cancelFun 取消密码输入的fun
 * @passwordBoxClss 密码框的className
 */

interface IProps {
  num: number,
  titleText?: string,
  callBack: Function,
  cancelFun: Function,
  passwordBoxClss?: string
}

const Index: FC<IProps> = (props: IProps) => {
  const [focusFlag, setFocusFlag] = useState<number>(1);
  const [value, setValue] = useState('');
  const { num, titleText, callBack, cancelFun, passwordBoxClss } = props;

  return (
    <View className={styles.password_cover}>

      <View className={styles.password_box}>
        <View className={styles.title}>
          <Text className={styles.cancel} onClick={() => cancelFun()}>X</Text>
          {titleText || '请输入密码'}
        </View>

        <View className={styles.text_ipt} onClick={() => setFocusFlag(focusFlag + 1)}>
          {
            Array.from(Array(num), (item, index) => index).map((item, idx) => (
              <Text className={classnames(idx == 0 ? styles.password_act : '', passwordBoxClss || '', styles.password_text)}>
                {value[idx] ? <Text className={styles.block_circle}/>  : ''}
              </Text>
            ))
          }
        </View>
      </View>

      <Input
        type="number"
        password
        focus={!!focusFlag}
        maxLength={num}
        onInput={(e: any) => {
          setValue(e.detail.value.trim() || '')
          if (e.detail.value.trim().length == num) {
            callBack()
            setFocusFlag(0)
          }
          return {
            value: e.detail.value.trim() || ''
          }
        }}
      />
    </View>
  )
}
export default Index
